const MiniCssExtractPlugin = require('mini-css-extract-plugin');

// Generate various css language loader
function createStyleLoaders(options = {}) {
  const { sourceMap, minimize, extract, postcss, cache } = options;
  const output = [];
  const cssLoader = {
    loader: 'css-loader',
    options: { minimize, sourceMap }
  };
  const postcssLoader = {
    loader: 'postcss-loader',
    options: { sourceMap }
  };

  // generate loader string to be used with extract text plugin
  function generateLoaders(loader, loaderOptions = {}) {
    const loaders = [ cssLoader ];
    if (cache) loaders.unshift('cache-loader');
    if (postcss) loaders.push(postcssLoader);
    if (loader) {
      loaders.push({
        loader: `${ loader }-loader`,
        options: { ...loaderOptions, sourceMap }
      });
    }
    // Extract CSS when that option is specified
    // (which is the case during production build)
    return [ extract ? MiniCssExtractPlugin.loader : 'style-loader' ].concat(loaders);
  }

  // https://vue-loader.vuejs.org/en/configurations/extract-css.html
  const loaders = {
    css: generateLoaders(),
    postcss: generateLoaders(),
    less: generateLoaders('less'),
    sass: generateLoaders('sass', { indentedSyntax: true }),
    scss: generateLoaders('sass')
  };

  for (let extension in loaders) {
    let loader = loaders[ extension ];
    output.push({
      test: new RegExp('\\.' + extension + '$'),
      use: loader
    });
  }

  return output;
};

module.exports = createStyleLoaders;
